package com.download;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.databasefunction.AllDBFunction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadUserAction extends ActionSupport{
	private InputStream fileInputStream;
	 
	public InputStream getFileInputStream() {
		return fileInputStream;
	}
 
	public String execute() throws Exception {
	    //Function to generate file
		String userrole = (String) ActionContext.getContext().getSession().get("userrole");
		if ((null != userrole) && ( userrole.equals("admin") || userrole.equals("superadmin"))) {
			
		}else
			return "unauthorised";
		
		AllDBFunction allDBFunction = new AllDBFunction();
		HashMap businessMap = allDBFunction.getDealerData();
		
		File file = new File("downloaduserinfo.csv");
		if (file.exists()) {
			file.delete();
			file.createNewFile();
		}else{
			file.createNewFile();
		}
		
		FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		
		Iterator iterator = businessMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Entry) iterator.next();
			HashMap hashMap = new HashMap();
			hashMap = (HashMap) entry.getValue();
			Iterator iterator2 = hashMap.entrySet().iterator();
			
			while (iterator2.hasNext()) {
				Map.Entry entry2 = (Entry) iterator2.next();
				bufferedWriter.write((String)entry2.getValue()+",");
				
			}
			bufferedWriter.newLine();
		}
		bufferedWriter.close();
		fileWriter.close();
		
		fileInputStream = new FileInputStream(new File("downloaduserinfo.csv"));
	    return SUCCESS;
	}
}